package com.xiaoma.weblog.admin.service.impl;

import com.xiaoma.weblog.admin.model.vo.user.FindUserInfoRspVO;
import com.xiaoma.weblog.admin.model.vo.user.UpdateAdminUserPasswordReqVO;
import com.xiaoma.weblog.admin.service.AdminUserService;
import com.xiaoma.weblog.common.domain.mapper.UserMapper;
import com.xiaoma.weblog.common.enums.ResponseCodeEnum;
import com.xiaoma.weblog.common.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @ClassName AdminUserServiceImpl
 * @Description:
 * @Author: 小马
 * @CreateDate: 2025/3/28 9:54
 * @Version: 1.0
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Response<Object> updatePassword(UpdateAdminUserPasswordReqVO updateAdminUserPasswordReqVO) {
        String username = updateAdminUserPasswordReqVO.getUsername();
        String password = updateAdminUserPasswordReqVO.getPassword();
        String newPassword = passwordEncoder.encode(password);
        int count = userMapper.updatePassword(username, newPassword);
        return count == 1 ? Response.success() : Response.fail(ResponseCodeEnum.USERNAME_NOT_FOUND.getErrorMessage());
    }

    @Override
    public Response<FindUserInfoRspVO> findUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String userName = authentication.getName();
        return Response.success(FindUserInfoRspVO.builder().username(userName).build());
    }
}